package com.example.newsapp.fragment;

import static com.example.newsapp.constant.NetConstant.BASE_URL;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.newsapp.activity.ProfileActivity;
import com.example.newsapp.adapter.NewsAdapter;
import com.example.newsapp.model.NewsItem;
import com.example.newsapp.R;
import com.example.newsapp.model.Result;
import com.example.newsapp.utils.HttpUtil;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NewsFragment extends Fragment implements View.OnClickListener {
    private RecyclerView newsRecyclerView;
    private NewsAdapter newsAdapter;
    private List<NewsItem> newsList;
    private TextView currentSelectedTag;
    private Map<String, Integer> categoryMap;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news, container, false);
        initViews(view);
        initCategoryMap();
        setupRecyclerView();
        loadNewsByCategory("科技"); // 默认加载科技新闻
        return view;
    }

    private void initViews(View view) {
        newsRecyclerView = view.findViewById(R.id.newsRecyclerView);
        // 初始化标签并设置点击监听
        TextView tagTechnology = view.findViewById(R.id.tagTechnology);
        TextView tagEntertainment = view.findViewById(R.id.tagEntertainment);
        TextView tagSports = view.findViewById(R.id.tagSports);
        TextView tagMilitary = view.findViewById(R.id.tagMilitary);
        TextView tagAuto = view.findViewById(R.id.tagAuto);
        TextView tagHealth = view.findViewById(R.id.tagHealth);

        tagTechnology.setOnClickListener(this);
        tagEntertainment.setOnClickListener(this);
        tagSports.setOnClickListener(this);
        tagMilitary.setOnClickListener(this);
        tagAuto.setOnClickListener(this);
        tagHealth.setOnClickListener(this);

        // 默认选中科技标签
        currentSelectedTag = tagTechnology;
        updateTagSelection(currentSelectedTag);
    }

    private void setupRecyclerView() {
        newsList = new ArrayList<>();
        newsAdapter = new NewsAdapter(newsList);
        newsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        newsRecyclerView.setAdapter(newsAdapter);
    }

    private void initCategoryMap() {
        categoryMap = new HashMap<>();
        categoryMap.put("科技", 1);
        categoryMap.put("娱乐", 2);
        categoryMap.put("体育", 3);
        categoryMap.put("军事", 4);
        categoryMap.put("汽车", 5);
        categoryMap.put("健康", 6);
    }

    private void loadNewsByCategory(String category) {
        Integer categoryId = categoryMap.get(category);
        newsList.clear();
        if (categoryId == null) {
            Toast.makeText(getContext(), "分类不存在，加载失败", Toast.LENGTH_SHORT).show();
        }
        requestNewsItemByCategoryId(categoryId);
    }

    private void requestNewsItemByCategoryId(Integer categoryId) {
        String requestUrl = BASE_URL + "/news/category/" + categoryId;
        Type resultType = new TypeToken<Result<List<NewsItem>>>() {
        }.getType();
        HttpUtil.request(getContext(),requestUrl, "GET", null, resultType, new HttpUtil.Callback<Result<List<NewsItem>>>() {
            @Override
            public void onSuccess(Result<List<NewsItem>> result) {
                handleNewsItemResponse(result);
            }

            @Override
            public void onFailure(Exception e) {
                showToast("查询出错");
            }
        });
    }

    private void handleNewsItemResponse(Result<List<NewsItem>> response) {
        if (response == null) {
            showToast("服务器响应异常");
            return;
        }

        if (response.getCode() == 1 && response.getData() != null) {
            List<NewsItem> items = response.getData();
            newsList.addAll(items);
            newsAdapter.notifyDataSetChanged();
        } else {
            String errorMsg = response.getMsg();
            if (errorMsg == null || errorMsg.isEmpty()) errorMsg = "未知错误";
            showToast("获取+" + currentSelectedTag.getText() + "列表失败：" + errorMsg);
        }
    }

    @Override
    public void onClick(View v) {
        TextView selectedTag = (TextView) v;
        if (currentSelectedTag != selectedTag) {
            updateTagSelection(selectedTag);
            String category = selectedTag.getText().toString();
            loadNewsByCategory(category);
            Toast.makeText(getContext(), "已切换到: " + category, Toast.LENGTH_SHORT).show();
        }
    }

    private void updateTagSelection(TextView selectedTag) {
        // 重置之前选中标签的样式
        if (currentSelectedTag != null) {
            currentSelectedTag.setBackgroundResource(android.R.color.transparent);
            currentSelectedTag.setAlpha(0.7f);
        }

        // 设置新选中标签的样式
        selectedTag.setBackgroundResource(R.drawable.selected_tag_background);
        selectedTag.setAlpha(1.0f);
        currentSelectedTag = selectedTag;
    }

    private void showToast(String msg) {
        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
    }
}